package com.monkeyk.sos.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Service;

import com.monkeyk.sos.domain.model.ApplicationDetails;
import com.monkeyk.sos.domain.model.CooperDetails;
import com.monkeyk.sos.service.SysApplicationService;
import com.monkeyk.sos.util.CurrentPage;
import com.monkeyk.sos.util.Pager;
import com.monkeyk.sos.util.PaginationHelper;

/**
 * 
 * 
 ***************************************************************  
 * <b>项目名称：</b>腾邦开放平台<br>
 * <b>程序名称：</b>应用服务业务层<br>
 * <b>日期：</b>2015年12月9日 下午2:42:14<br>
 * <b>作者：</b>Haiquan Yin<br>
 * <b>模块： </b>应用服务管理<br>
 * <b>描述： </b>业务实现层<br>
 * <b>备注： </b><br>
 * ------------------------------------------------------------ 
 * 修改历史 
 * ------------------------------------------------------------ 
 * 序号               日期                       修改人                   修改原因 
 * ------------------------------------------------------------  
 *  
 * 修改备注： 
 * <p>@version</p>
 * <p></p>
 ***************************************************************
 */
@Service
public class SysApplicationServiceImpl extends JdbcDaoSupport implements SysApplicationService {

	@Resource(name = "dataSource")
	public void setRegionDataSource(DataSource dataSource) {
		super.setDataSource(dataSource);
	}
	
	/**
	 * 
	 * TODO 审核应用状态
	 * @date 2015年12月18日 下午3:47:52 
	 * @author Haiquan Yin
	 * @param ids
	 * @param status
	 */
	@Override
	public void updateAppType(List<Integer> ids, int status) {
		if (null!=ids&&ids.size()>0) {
			String sql = "UPDATE application_details SET status = ? WHERE id = ?";
			for (int i = 0; i < ids.size(); i++) {
				this.getJdbcTemplate().update(sql, new Object[]{status,ids.get(i)});
			}
		}
	}

	/**
	 * 
	 * TODO 分页查询应用信息
	 * @date 2015年12月9日 下午2:50:24 
	 * @author HaiQuan Yin
	 * @param paramMap 查询条件
	 *                 appName  应用名称
	 *                 status   审核状态
	 * @param pager    分页信息
	 * @return
	 */
	public Pager findApps(Map<String, Object> paramMap, Pager pager) {
		Object [] objects = null;
		String applicationName = null;
		int status = -1;
		PaginationHelper<ApplicationDetails> ph = new PaginationHelper<ApplicationDetails>();
		StringBuffer sql = new StringBuffer();
		StringBuffer sqlCount = new StringBuffer();
		sql.append("SELECT * FROM application_details a WHERE 1=1");
		sqlCount.append("SELECT COUNT(*) FROM application_details a WHERE 1=1");
		if (null!=paramMap) {
			 applicationName = (String) paramMap.get("appName");
			 status = (Integer) paramMap.get("status");
		}
		
		if (null!=applicationName&&!"".equals(applicationName)) {
			sql.append(" and (a.app_name like '%"+applicationName+"%' or a.web_name like '%"+applicationName+"%')");
			sqlCount.append(" and a.app_name like '%"+applicationName+"%' or a.web_name like '%"+applicationName+"%')");
			objects = new Object[]{};
		}
		
		if (-1!=status) {
			sql.append(" and a.status = ?");
			sqlCount.append(" and a.status = ?");
			objects = new Object[]{status};
		}
		
		CurrentPage<ApplicationDetails> p =  ph.fetchPage(super.getJdbcTemplate(),
				sqlCount.toString(), 
				sql.toString(), 
				objects, 
				pager.getPage(), 
				pager.getPageSize(), 
				new ParameterizedRowMapper<ApplicationDetails>() {
					@Override
					public ApplicationDetails mapRow(ResultSet rs, int arg1)
							throws SQLException {
						ApplicationDetails apd = new ApplicationDetails();
						apd.setAppId(rs.getLong("id"));
						apd.setAppDescribe(rs.getString("app_describe"));
						apd.setAppName(rs.getString("app_name"));
						apd.setAppPlatform(rs.getString("app_platform"));
						apd.setAppProfile(rs.getString("app_profile"));
						apd.setCreateDate(rs.getTimestamp("t_createdate").toString());
						apd.setStatus(rs.getInt("status"));
						apd.setUpdateDate(rs.getTimestamp("t_updatedate").toString());
						apd.setWebDomains(rs.getString("web_domains"));
						apd.setWebName(rs.getString("web_name"));
						apd.setWebRecord(rs.getString("web_record"));
						return apd;
					}
				});
		pager.setData(p.getPageItems());
		pager.setTotalResults(p.getTotals());
		return pager;
	}

	/**
	 * 
	 * TODO 根据合作者ID获取合作者详情信息
	 * @date 2015年12月18日 下午3:48:21 
	 * @author Haiquan Yin
	 * @param coopId 合作者ID
	 * @return
	 */
	@Override
	public CooperDetails findCooperDetailById(int coopId) {
		String sql = "SELECT * FROM cooperator a WHERE id="+coopId;
		List<CooperDetails> list = null;
		
		list = this.getJdbcTemplate().query(sql, new RowMapper<CooperDetails>(){
			@Override
			public CooperDetails mapRow(ResultSet arg0, int arg1) throws SQLException {
				CooperDetails cDetails = new CooperDetails();
				cDetails.setCooperId(arg0.getLong("id"));
				cDetails.setCooperName(arg0.getString("cooper_name"));
				cDetails.setEmail(arg0.getString("email"));
				cDetails.setPhone(arg0.getString("phone"));
				cDetails.setStatus(arg0.getInt("status"));
				cDetails.setDefaultUser(arg0.getInt("default_user"));
				cDetails.setAddress(arg0.getString("address"));
				cDetails.setProvince(arg0.getString("province"));
				cDetails.setCity(arg0.getString("city"));
				cDetails.setContactPerson(arg0.getString("contact_person"));
				cDetails.setContactPhone(arg0.getString("contact_phone"));
				cDetails.setOrganization(arg0.getString("c_organization"));
				cDetails.setLicenseNumber(arg0.getString("c_license_number"));
				cDetails.setLicenseImgFrontURL(arg0.getString("c_license_img_front_url"));
				cDetails.setLicenseImgBackURL(arg0.getString("c_license_img_back_url"));
				cDetails.setIdCard(arg0.getString("c_id_card"));
				cDetails.setIdCardImgFrontURL(arg0.getString("c_id_card_img_front_url"));
				cDetails.setIdCardImgBackURL(arg0.getString("c_id_card_img_back_url"));
				cDetails.setLegalPersonName(arg0.getString("c_legal_person_name"));
				cDetails.setLegalPersonPhone(arg0.getString("c_legal_person_phone"));
				cDetails.setCoopType(arg0.getInt("i_coop_type"));
				cDetails.setPercent(arg0.getInt("i_percent"));
				return cDetails;
			}
		});
		return (null!=list&&list.size()>0)?list.get(0):null;
	}

	/**
	 * 
	 * TODO 根据应用ID获取合作者ID
	 * @date 2015年12月18日 下午4:27:41 
	 * @author Haiquan Yin
	 * @param appId 应用ID
	 * @return
	 */
	@Override
	public int findCoopIDByAppId(int appId) {
        String sql ="SELECT  cooper_id FROM cooper_app WHERE app_id ="+appId;
        List<Integer> list = null;
        list = this.getJdbcTemplate().query(sql,new RowMapper<Integer> (){
			@Override
			public Integer mapRow(ResultSet arg0, int arg1) throws SQLException {
				return arg0.getInt(1);
			}
        });
		
		return (null!=list&&list.size()>0)?list.get(0):0;
	}

}
